class MPromise{
    // 状态 + 结果
    PromiseState = 'padding'
    PromiseResult = undefined
    
    // 回调函数库
    fulfilledCds = []
    rejectedCds = []

    // 构造函数
    constructor(executor){
        // 捕获执行器中非"reject"异常
        try {
            executor(
                this.resolve.bind(this),
                this.reject.bind(this)
            )   
        } catch (error) {
            this.reject(error)
        }
    }

    /**
     * 成功回调
     * @param {*} event 
     * 更新状态，并保存结果
     */
    resolve(event){
        if(this.PromiseState == 'padding'){
            this.PromiseState = 'fulfilled'
            this.PromiseResult = event
        }
        // 遍历执行成功函数库中函数
        while(this.fulfilledCds.length){
            this.fulfilledCds.shift()(this.PromiseResult)
        }
    }

    /**
     * 失败回调
     * @param {*} event 
     * 更新状态，并保存结果
     */
    reject(event){
        if(this.PromiseState == 'padding'){
            this.PromiseState = 'rejected'
            this.PromiseResult = event
        }
        // 遍历执行失败函数库中函数
        while(this.rejectedCds.length){
            this.rejectedCds.shift()(this.PromiseResult)
        }
    }

    /**
     * 接收两个回调函数
     * 根据当前状态执行对应回调函数
     * 如果是pdding状态，则将两个回调函数保存
     * @param {*} 
     *      onFulfilled 成功回调 
     *      onRejected 失败回调 
     * @returns 
     */
    then(onFulfilled, onRejected){
        // 判断入参是否为函数
        onFulfilled = (onFulfilled instanceof Function) ? onFulfilled : val => val
        onRejected = (onRejected instanceof Function) ? onRejected : reas
        switch (this.PromiseState) {
            case 'padding':
                this.fulfilledCds.push(onFulfilled)
                this.rejectedCds.push(onRejected)
                break;
            case 'fulfilled':
                this.fulfilledCds.push(onFulfilled)
                break;
            case 'rejected': 
                this.rejectedCds.push(onRejected)
                break;
            default:
                break;
        }
        return this
    }

}